package com.stu.day17;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author zy
 * @date 2025/2/18 15:41
 */
public class CallableDemo implements Callable<Integer> {
    static int count = 0;
    static int sum = 0;
    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 10; i++) {
            add();
        }
        Thread.sleep(1000);
        return Integer.valueOf(sum);
    }
    public synchronized void add(){
        System.out.println(Thread.currentThread().getName());
        count++;
        sum += count;
    }
}
class CallableTest{
    public static void main(String[] args) {
        Callable callable = new CallableDemo();
        FutureTask f = new FutureTask(callable);
        FutureTask f2 = new FutureTask(callable);
        Thread t1 = new Thread(f);
        Thread t2 = new Thread(f2);
        Thread t3 = new Thread(f);
        Thread t4 = new Thread(f);
        Thread t5 = new Thread(f);
        Thread t6 = new Thread(f);
        Thread t7 = new Thread(f);
        Thread t8 = new Thread(f);
        Thread t9 = new Thread(f);
        Thread t10 = new Thread(f);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        t9.start();
        t10.start();

        try {
            Thread.sleep(2000);
            Integer result = (Integer) f.get();
            System.out.println("result:"+result);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
